<template>
<dic>
  <div class="home">
    <div class="box-pie" id="main1" style="height: 400px" ref="chart"></div>
  </div>
</dic>
</template>

<script>
export default {
  name: "web",
  data () {
    return {
      option:{
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [],
            type: 'line',
            smooth: true
          }
        ]
      },
      myChart:null,
      wsUrl: 'ws://localhost:8888/test/oneToMany', // ws地址
      websock: null, // ws实例
    }
  },
  mounted() {
    //初始化表格
    this.initEcharts();
    this.initWebSocket();//初始化websocket
  },

  destroyed() {
    // 离开路由之后断开websocket连接
    this.websock.close()
  },
  methods:{
    // 初始化weosocket
    initWebSocket() {
      if (typeof WebSocket === 'undefined')
        return console.log('您的浏览器不支持websocket')
      this.websock = new WebSocket(this.wsUrl)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen() {
      // 连接建立之后执行send方法发送数据
      let actions = { test: 'test' }
      this.websocketsend(JSON.stringify(actions))
    },
    websocketonerror() {
      // 连接建立失败重连
      this.initWebSocket()
    },
    websocketonmessage(e) {
      // 数据接收
      const redata = e.data
      console.log('接收的数据', redata)//d
      if(this.option.series[0].data.length==24){
        this.option.series[0].data.shift() //删除第一个元素
      }
      if(this.option.xAxis.data.length==24){
        this.option.xAxis.data.shift();
      }
      this.option.xAxis.data.push(this.getCurrentTime())
      this.option.series[0].data.push(redata) //往图形报表中的数组添加元素
      this.initEcharts();
    },
    websocketsend(Data) {
      // 数据发送
      this.websock.send(Data)
    },
    websocketclose(e) {
      // 关闭
      console.log('断开连接', e)
    },

    initEcharts(){
      var elementById = document.getElementById("main1");
      this.myChart = this.$echarts.init(elementById);
      this.myChart.setOption(this.option);
    },
    getCurrentTime() {
      var date = new Date();//当前时间
      var year = date.getFullYear() //返回指定日期的年份
      var month = this.repair(date.getMonth() + 1);//月
      var day = this.repair(date.getDate());//日
      var hour = this.repair(date.getHours());//时
      var minute = this.repair(date.getMinutes());//分
      var second = this.repair(date.getSeconds());//秒

      //当前时间
      var curTime = year + "-" + month + "-" + day
        + " " + hour + ":" + minute + ":" + second;
      return curTime;
    }

//补0
    ,
    repair(i){
      if (i >= 0 && i <= 9) {
        return "0" + i;
      } else {
        return i;
      }
    }

  }
}
</script>

<style scoped>

</style>
